# 1. 导入依赖库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from utils.LinearRegression.LinearRegressionUtils import LinearRegression

# 2. 加载数据集
data = pd.read_csv('../static/data/non-linear-regression-x-y.csv')
x = data['x'].values.reshape(-1, 1)
y = data['y'].values.reshape(-1, 1)

# 3. 设置特征变换阶数以及sin变换阶数，训练数据集
polynomial_degree = 15
sinusoid_degree = 15
normalize_data = True

# 4. 实例化LinearRegression类，进行训练
linear_regression = LinearRegression(y, x,polynomial_degree, sinusoid_degree, normalize_data)
alpha = 0.02
iterations = 50000
cost_history = linear_regression.train(alpha, iterations)
print('Cost before training:', cost_history[0])
print('Cost after training:', cost_history[-1])


# 5. 绘制训练过程中的损失函数，即结果展示
plt.rcParams['font.sans-serif'] = ['SimHei']  # 设置字体为黑体
plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示为方块的问题
plt.plot(np.arange(iterations), cost_history)
plt.xlabel('Iterations')
plt.ylabel('Cost')
plt.title('损失函数曲线图')
plt.show()

# 6. 显示预测曲线
predictions_num = 100
# 显示数据图
plt.plot(x,y)
# 显示预测曲线
x_min = data['x'].values.min()
x_max = data['x'].values.max()
x_test = np.linspace(x_min, x_max, predictions_num).reshape(-1, 1)
prediction_y = linear_regression.get_predict(x_test).flatten()
plt.plot(x_test, prediction_y)
plt.xlabel('x')
plt.ylabel('y')
plt.title('预测曲线图')
plt.show()


